import { createStore } from 'vuex'
import user from './modules/user'

export default createStore({
  state: {
    plans: [],
    checkIns: []
  },
  modules: {
    user
  },
  mutations: {
    SET_PLANS(state, plans) {
      state.plans = plans
    },
    ADD_PLAN(state, plan) {
      state.plans.push(plan)
    },
    UPDATE_PLAN(state, updatedPlan) {
      const index = state.plans.findIndex(p => p.id === updatedPlan.id)
      if (index !== -1) {
        state.plans.splice(index, 1, updatedPlan)
      }
    },
    ADD_CHECK_IN(state, checkIn) {
      state.checkIns.push(checkIn)
    }
  },
  actions: {
    createPlan({ commit }, planData) {
      const plan = {
        id: Date.now().toString(),
        ...planData,
        status: 'active',
        createdAt: new Date().toISOString(),
        completedDays: 0
      }
      commit('ADD_PLAN', plan)
      return plan
    },
    checkIn({ commit, state }, { planId, note }) {
      const plan = state.plans.find(p => p.id === planId)
      if (!plan) return

      const checkIn = {
        id: Date.now().toString(),
        planId,
        date: new Date().toISOString().split('T')[0],
        time: new Date().toTimeString().split(' ')[0],
        note,
        onTime: true
      }

      const updatedPlan = {
        ...plan,
        completedDays: plan.completedDays + 1
      }

      if (updatedPlan.completedDays >= plan.totalDays) {
        updatedPlan.status = 'completed'
      }

      commit('ADD_CHECK_IN', checkIn)
      commit('UPDATE_PLAN', updatedPlan)

      return checkIn
    },
    initializeData({ commit }) {
      const plans = [
        {
          id: '1',
          title: '每日阅读',
          description: '每天阅读30分钟，提升自己',
          type: 'daily',
          status: 'active',
          startDate: '2024-01-01',
          endDate: '2024-01-30',
          createdAt: '2024-01-01',
          completedDays: 15,
          totalDays: 30
        },
        {
          id: '2',
          title: '运动健身',
          description: '每周至少运动3次，保持健康',
          type: 'weekly',
          status: 'active',
          startDate: '2024-01-01',
          endDate: '2024-03-31',
          createdAt: '2024-01-02',
          completedDays: 6,
          totalDays: 12
        }
      ]

      const checkIns = [
        {
          id: '1',
          planId: '1',
          date: '2024-01-15',
          time: '08:30:00',
          onTime: true,
          note: '今天读完了一章'
        },
        {
          id: '2',
          planId: '1',
          date: '2024-01-14',
          time: '23:50:00',
          onTime: false,
          note: '差点忘记打卡了'
        }
      ]

      commit('SET_PLANS', plans)
      checkIns.forEach(checkIn => commit('ADD_CHECK_IN', checkIn))
    }
  }
})